#!/usr/bin/env bash
#
# narsil-hostname.sh - Change system hostname
# Seaton Jiang <hi@seatonjiang.com>
#
# The latest version of Narsil can be found at:
# https://github.com/seatonjiang/narsil
#
# Copyright (C) 2023 Seaton Jiang
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.

function narsil_hostname()
{
    narsil_hostname='rockylinux'
    old_hostname=$(hostname)

    if [[ ${METADATA} == "Y" ]]; then
        if [ -n "$(wget -qO- -t1 -T2 metadata.tencentyun.com)" ]; then
            new_hostname=$(wget -qO- -t1 -T2 metadata.tencentyun.com/latest/meta-data/instance-name)
        fi
    fi

    if [ "${narsil_hostname}" != "${HOSTNAME}" ]; then
        new_hostname=${HOSTNAME}
    fi

    if [ "${new_hostname}" == "未命名" ]; then
        new_hostname='rockylinux'
    fi

    msg_notic '\n%s' "[1/2] Please enter hostname (current is ${new_hostname}): "

    read -r new_hostname

    hostnamectl set-hostname --static "${new_hostname}"
    sed -i "s@${old_hostname}@${new_hostname}@g" /etc/hosts
    sed -i '/update_hostname/d' /etc/cloud/cloud.cfg

    msg_notic '\n%s\n' "[2/2] Show file content: /etc/hosts"
    grep -Ev '^#|^$' /etc/hosts | uniq
    msg_succ '\n%s\n\n' "Hostname has been changed successfully!"

    exit 0
}
